/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;

namespace Xceed.Silverlight.Data
{
  internal abstract class DataRangeEnumeratorBase : IDataRangeEnumerator
  {
    #region Static Fields

    private static readonly Guid GetNextCallId = DataUtils.CreateCallId();

    #endregion


    protected DataRangeEnumeratorBase()
    {
    }


    #region IsGettingNext Property

    public bool IsGettingNext
    {
      get
      {
        return m_isGettingNext;
      }
      private set
      {
        if( value != m_isGettingNext )
        {
          m_isGettingNext = value;

          if( !value )
          {
            this.OnGetNextCompleted( EventArgs.Empty );
          }
        }
      }
    }

    private bool m_isGettingNext; //false

    #endregion

    #region HasMore Property (Protected)

    protected virtual bool HasMore
    {
      get
      {
        return !m_disposed;
      }
    }

    #endregion


    #region GetNextCompleted Event

    public event EventHandler GetNextCompleted;

    private void OnGetNextCompleted( EventArgs e )
    {
      if( this.GetNextCompleted != null )
      {
        this.GetNextCompleted( this, e );
      }
    }

    #endregion


    public IAsyncResult BeginGetNext( AsyncCallback callback, object state )
    {
      this.CheckState();

      AsyncResult asyncResult;

      // We already know there is no more item.
      if( !this.HasMore )
      {
        asyncResult = new AsyncResult( DataRangeEnumeratorBase.GetNextCallId, callback, state );
        asyncResult.StartSync( new GetNextResult() );
      }
      else
      {
        // This anonymous method resets the IsGettingNext flag when the item is fetched.
        AsyncCallback resetFlag =
          ( IAsyncResult ar ) =>
          {
            // This call will raise the GetNextCompleted event
            this.IsGettingNext = false;

            // This call will execute the user callback 
            if( callback != null )
            {
              callback.Invoke( ar );
            }
          };

        asyncResult = new AsyncResult( DataRangeEnumeratorBase.GetNextCallId, resetFlag, state );

        try
        {
          this.IsGettingNext = true;

          asyncResult.Start(
            this.BeginGetNextCore,
            ( par, iar ) => new DependentCallResult( this.EndGetNextCore( iar ) ) );
        }
        catch( Exception )
        {
          this.IsGettingNext = false;
          throw;
        }
      }

      return asyncResult;
    }

    public GetNextResult EndGetNext( IAsyncResult asyncResult )
    {
      asyncResult.ValidateCallEnd( DataRangeEnumeratorBase.GetNextCallId );

      return asyncResult.GetCallResult<GetNextResult>();
    }

    public abstract void Reset();

    protected abstract IAsyncResult BeginGetNextCore( AsyncCallback callback, object state );
    protected abstract GetNextResult EndGetNextCore( IAsyncResult asyncResult );

    protected void CheckState()
    {
      this.CheckDisposed();
      this.CheckGetNext();
    }

    private void CheckDisposed()
    {
      if( m_disposed )
        throw new ObjectDisposedException( "The current enumerator has been disposed." );
    }

    private void CheckGetNext()
    {
      if( m_isGettingNext )
        throw new InvalidOperationException( "The enumerator is currently moving next." );
    }


    #region IDispose Members

    public void Dispose()
    {
      this.Dispose( true );
      GC.SuppressFinalize( this );
    }

    protected virtual void Dispose( bool disposing )
    {
      this.GetNextCompleted = null;

      m_disposed = true;
    }

    ~DataRangeEnumeratorBase()
    {
      this.Dispose( false );
    }

    private bool m_disposed; //false

    #endregion
  }
}
